<template>
  <div class="blog-list">
    <div class="list-serach">
      <a-input-search
        v-if="this.user.type === '2'"
        size="default"
        v-model="proId"
        placeholder="请输入项目id"
        enter-button
        @search="searchByProId"
      />
      <a-input-search
        size="default"
        v-model="searchId"
        placeholder="请输入文章id"
        enter-button
        @search="searchById"
      />
      <a-input-search
        size="default"
        v-model="keyword"
        placeholder="请输入文章标题或内容关键词"
        enter-button
        @search="searchByKeyWord"
      />
      <a-button type="primary" @click="resetSearch">重置搜索条件</a-button>
    </div>
    <a-table
      :row-selection="{
        selectedRowKeys: selectedRowKeys,
        onChange: onSelectChange,
      }"
      :columns="columns"
      :data-source="blogList"
      :pagination="false"
      :rowKey="(record) => record.id"
    >
      <span slot="customTitle">博客id</span>
      <span slot="pic" slot-scope="text, record">
        <img
          style="height:100px;border-radius: 5%;box-shadow: 2px 2px 5px #333333;"
          :src="record.cover"
        />
      </span>
      <span slot="action">
        <a-button
          type="primary"
          style="margin-right:8px"
          icon="eye"
          @click="showDetail"
          >查看</a-button
        >
        <a-button
          type="danger"
          style="margin-right:8px"
          icon="delete"
          @click="delSingle"
          >删除</a-button
        >
      </span>
    </a-table>
    <div class="bottom">
      <a-button type="danger" class="del-list-btn" @click="delAll"
        >删除选中</a-button
      >

      <a-pagination
        class="pageTab"
        show-quick-jumper
        :current="current"
        :page-size-options="pageSizeOptions"
        :total="blogNum"
        :show-total="(total) => `共 ${blogNum} 条微博`"
        :page-size="limit"
        :default-current="1"
        show-size-changer
        @showSizeChange="onShowSizeChange"
        @change="pageChange"
      />
      <a-modal
        centered
        title="删除博客"
        v-model="isDel"
        @ok="delOk"
        @cancel="delNo"
      >
        <p>确定删除这条博客吗？(此操作不可逆噢～)</p>
      </a-modal>
      <a-modal
        centered
        title="删除博客"
        v-model="isDelAll"
        @ok="delAllOk"
        @cancel="delAllNo"
      >
        <p>确定删除选中博客吗？(此操作不可逆噢～)</p>
      </a-modal>
    </div>
  </div>
</template>

<script>
import { mapGetters } from 'vuex';
import {
  blogListApi,
  delBlogApi,
  searchByIdApi,
  searchByKeyWordsApi,
  // adminGetAllBlogApi,
  // getArticleById,
  // searchArticle,
  // blogDetailApi,
} from '@/services/blogApi/blog';
// import { getProBLogApi } from '@/services/superAdmin';
import moment from 'moment';
export default {
  data() {
    return {
      columns: [
        {
          title: '文章id',
          dataIndex: 'id',
          key: 'blogId',
        },
        {
          title: '文章标题',
          dataIndex: 'title',
          key: 'title',
        },
        {
          title: '封面图片',
          dataIndex: 'cover',
          key: 'cover',
          scopedSlots: { customRender: 'pic' },
        },
        {
          title: '项目id',
          dataIndex: 'projectId',
          key: 'projectId',
        },
        {
          title: '文章作者',
          dataIndex: 'userName',
          key: 'userName',
        },
        {
          title: '创建时间',
          dataIndex: 'createdAt',
          key: 'createdAt',
        },
        // {
        //   title: '最近更新',
        //   dataIndex: 'updatedAt',
        //   key: 'updatedAt',
        // },
        {
          title: '操作',
          key: 'action',
          scopedSlots: { customRender: 'action' },
        },
      ],
      keyword: '',
      searchId: '',
      proId: '',
      blogNum: 0, //博客数量
      pageSizeOptions: ['5', '10', '15', '20', '25'], //每页文章数选择
      current: 1, //当前页面
      limit: 5, //每页多少条微博
      blogList: [],
      selectedRowKeys: [], //选择的列数
      projectId: 0,
      isDel: false,
      isDelAll: false,
      currentBlogId: 0,
    };
  },
  computed: {
    ...mapGetters('account', ['user']),
  },
  async created() {
    this.getBlogList(this.limit, 0);
  },
  methods: {
    async resetSearch() {
      this.proId = '';
      this.keyword = '';
      this.searchId = '';
      this.getBlogList(this.limit, 0);
      this.$message.success(`重置搜索条件成功`, 1.5);
    },
    async searchByProId() {
      this.blogList = this.blogList.filter((item) => {
        return item.projectId == this.proId;
      });
    },
    async searchById() {
      try {
        let res = await searchByIdApi({
          id: this.searchId - 0,
          projectId: this.user.project_id,
        });
        if (res.data) {
          this.blogList = [];
          this.blogList.push(res.data);
        }
        this.blogNum = this.blogList.length;
      } catch (error) {
        this.searchId = '';
        this.getBlogList(this.limit, 0);
        return this.$message.error(`${error.msg},请重新输入`, 1);
      }
    },
    async searchByKeyWord() {
      try {
        let res = await searchByKeyWordsApi({
          keyword: this.keyword,
          projectId: this.user.project_id,
        });

        this.blogList = res.data;
        this.blogNum = res.data.length;
        // this.blogList.push(res.data)
      } catch (error) {
        this.keyword = '';
        this.getBlogList(this.limit, 0);
        return this.$message.error(`${error.msg},请重新输入`, 1);
      }
    },
    async getBlogList(limit, offset) {
      if (this.user.type === '2') {
        let res = await blogListApi({
          limit,
          offset,
          projectId: this.user.project_id,
        });
        this.projectId = this.user.project_id;
        this.blogList = res.data.rows;
        this.blogList.forEach((ele) => {
          ele.createdAt = moment(ele.createdAt).format('YYYY-MM-DD  HH:mm:ss');
          ele.updatedAt = moment(ele.updatedAt).format('YYYY-MM-DD  HH:mm:ss');
        });

        this.blogNum = res.data.count;
      } else {
        // let res = await getProBLogApi({
        //   limit,
        //   offset,
        // });
        // this.blogList = res.data.rows;
        // this.blogList.forEach((ele) => {
        //   ele.createdAt = moment(ele.createdAt).format('YYYY-MM-DD  HH:mm:ss');
        //   ele.updatedAt = moment(ele.updatedAt).format('YYYY-MM-DD  HH:mm:ss');
        // });
        // this.blogNum = res.data.count;
      }
    },
    async showDetail(e) {
      let tr = e.target.parentNode.parentNode.parentNode;
      let id = tr.children[1].innerHTML;
      this.$router.push(`/blog/blogDetail/${id}`);
    },
    async delSingle(e) {
      let tr = e.target.parentNode.parentNode.parentNode;
      let id = tr.children[1].innerHTML;
      this.currentBlogId = id;
      this.isDel = true;
    },
    //删除博客
    async delBlog(blogId) {
      await delBlogApi({
        blogId,
        projectId: this.projectId,
      });
    },
    delOk() {
      this.delBlog(this.currentBlogId);
      this.getBlogList(this.limit, 0);
      this.isDel = false;
      this.$message.success('删除成功', 1);
      this.current = 1;
    },
    delNo() {
      this.isDel = false;
      this.$message.info('取消删除', 1);
    },
    onSelectChange(selectedRowKeys) {
      this.selectedRowKeys = selectedRowKeys;
    },
    //-----
    delAll() {
      let flag = this.selectedRowKeys.length;
      if (flag == 0) {
        this.$message.error('未选中任何文章', 1);
      } else {
        this.isDelAll = true;
      }
    },
    delAllOk() {
      let delArr = this.selectedRowKeys;
      delArr.map((ele) => {
        this.delBlog(ele);
      });
      this.current = 1;
      this.getBlogList(this.limit, 0);
      this.$message.success(`成功删除${delArr.length}条博客`, 1);
      this.selectedRowKeys = [];
      this.isDelAll = false;
      location.reload();
    },
    delAllNo() {
      this.$message.info('取消删除', 1);
      this.isDelAll = false;
      location.reload();
    },
    //-----
    // 改变每页展示数量
    onShowSizeChange(current, pageSize) {
      this.limit = pageSize;
      this.pageChange(current);
    },
    /*
        不应该一次性请求所有文章，采用分页懒加载
      */
    pageChange(current) {
      this.current = current;
      let offset = (this.current - 1) * this.limit;
      this.getBlogList(this.limit, offset);
    },
  },
};
</script>

<style lang="scss" scoped>
.list-serach {
  display: flex;
  justify-content: space-around;
  gap: 1rem;
  margin-bottom: 1rem;
}
.bottom {
  display: flex;
  justify-content: space-between;
  margin-top: 1rem;
  .pageTab {
    text-align: right;
  }
  .del-list-btn {
    text-align: center;
  }
}
</style>
